import pygame
import sys
from game.game import Game
from game.game_mode import GameMode, RobotDifficulty
from ui.renderer import Renderer
from ui.menu import Menu
from ui.constants import WINDOW_WIDTH, WINDOW_HEIGHT


def main():
    pygame.init()

    screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
    pygame.display.set_caption("五子棋")
    clock = pygame.time.Clock()

    # 创建渲染器和菜单
    renderer = Renderer(screen)
    menu = Menu(screen, renderer.font)

    # 游戏状态
    game_state = "menu"  # menu, playing
    game = None

    # 按钮定义
    reset_btn = pygame.Rect(WINDOW_WIDTH // 4 - 60, WINDOW_HEIGHT - 60, 120, 40)
    undo_btn = pygame.Rect(WINDOW_WIDTH // 2 - 60, WINDOW_HEIGHT - 60, 120, 40)
    menu_btn = pygame.Rect(3 * WINDOW_WIDTH // 4 - 60, WINDOW_HEIGHT - 60, 120, 40)

    running = True
    while running:
        mouse_pos = pygame.mouse.get_pos()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:  # 左键点击
                    if game_state == "menu":
                        # 处理菜单点击
                        mode_result, difficulty_result = menu.handle_click(event.pos)
                        if mode_result:
                            # 开始游戏
                            game = Game(mode_result, difficulty_result)
                            game_state = "playing"

                    elif game_state == "playing":
                        # 游戏中的点击处理
                        if reset_btn.collidepoint(event.pos):
                            game.reset()

                        elif undo_btn.collidepoint(event.pos):
                            game.undo()

                        elif menu_btn.collidepoint(event.pos):
                            game_state = "menu"
                            menu.current_menu = "main"

                        else:
                            # 棋盘点击
                            row, col = renderer.get_board_pos(event.pos[0], event.pos[1])
                            if row is not None and col is not None:
                                game.handle_click(row, col)

        # 更新游戏逻辑
        if game_state == "playing" and game:
            game.update()

        # 绘制界面
        if game_state == "menu":
            menu.draw(mouse_pos)
        elif game_state == "playing" and game:
            renderer.draw_board()
            renderer.draw_stones(game.board)
            renderer.draw_status(game)
            renderer.draw_buttons(reset_btn, undo_btn, menu_btn, mouse_pos)

        pygame.display.flip()
        clock.tick(60)

    pygame.quit()
    sys.exit()


if __name__ == "__main__":
    main()
